import powerlaw
import numpy as np
import matplotlib.pyplot as plt
import tool
import mapping

"""
结果
Values less than or equal to 0 in data. Throwing out 0 or negative values
Calculating best minimal value for power law fit
拟合的幂律分布参数: alpha=2.876, xmin=6931.0
幂律分布与对数正态分布的对比: R=-0.414, p-value=0.529
不拒绝数据符合幂律分布的假设
"""


def long_tali_cal(data):
    fit = powerlaw.Fit(data)
    # 拟合参数
    alpha = fit.power_law.alpha
    xmin = fit.power_law.xmin
    print(f"拟合的幂律分布参数: alpha={alpha:.3f}, xmin={xmin}")

    # 绘制PDF（概率密度函数）
    plt.figure(figsize=(10, 6))
    fit.plot_pdf(label="Data", color="blue")
    fit.power_law.plot_pdf(label=f"Power law fit (alpha={alpha:.2f})", color="orange")
    plt.xlabel("Value")
    plt.ylabel("PDF")
    plt.title("PDF with Power Law Fit")
    plt.legend()
    plt.show()

    # KS检验结果
    R, p = fit.distribution_compare("power_law", "lognormal")
    print(f"幂律分布与对数正态分布的对比: R={R:.3f}, p-value={p:.3f}")

    # 判断假设检验结果
    if p < 0.05:
        print("拒绝数据符合幂律分布的假设")
    else:
        print("不拒绝数据符合幂律分布的假设")


def calculate_top_items_for_percentage(data, percentage=0.8):
    # 1. 将商品按销量从高到低排序
    sorted_data = np.sort(data)[::-1]

    # 2. 计算每个商品的累计销量占总销量的比例
    cumulative_sum = np.cumsum(sorted_data)
    total_sum = cumulative_sum[-1]
    cumulative_percentage = cumulative_sum / total_sum

    # 3. 找到占据指定总销量百分比的商品数量
    num_items = np.argmax(cumulative_percentage >= percentage) + 1

    return num_items, cumulative_percentage[:num_items]


def print_interesting_product(data):
    sorted_data = np.sort(data, order="total_quantity")[::-1]

    # 打印前10的商品代码和销量
    print("前10的商品代码及其销量:")
    for i in range(min(50, len(sorted_data))):  # 确保不会超过数据长度
        print(
            f"商品代码: {mapping.get_name(sorted_data[i]['code'])}, 销量: {sorted_data[i]['total_quantity']}"
        )


if __name__ == "__main__":
    # 输入数据
    data = tool.get_np("product_total_quantity.csv")
    # long_tali_cal(data["total_quantity"])
    num, result = calculate_top_items_for_percentage(data["total_quantity"])

    print_interesting_product(data)
